<template>
  <div
    v-if="formData != null"
    v-loading="isLoading"
    :element-loading-text="loadingMessage"
  >
    <div
      style="
        margin-bottom: 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      "
    >
      <span style="font-size: 16px; font-weight: bold">{{
        formData.title
      }}</span>
      <!-- <el-tag
        type="danger"
        size="medium"
        class="blinking-slow office-warning"
        effect="dark"
        >{{ formData.office }}</el-tag
      > -->
    </div>
    <el-alert type="info" :closable="false" class="notice-alert">
      <div>
        <span style="font-weight: bold; color: #f56c6c">
          {{ formData.year }}年度
        </span>
        <span style="padding: 0 6px">/</span>
        <span style="font-weight: bold; color: #f56c6c">
          {{ formData.office }}
        </span>
        <span style="padding: 0 6px">/</span>
        <span v-if="formData.type === 1" style="font-weight: bold">
          模拟机复训
        </span>
        <span v-if="formData.type === 2" style="font-weight: bold">
          模拟机专项训练
        </span>
        <span style="padding: 0 6px">/</span>
        <span v-if="formData.cycle > 0" style="font-weight: bold">
          第{{ formData.cycle }}期
        </span>
        <span v-else style="font-weight: bold"> 不计入得分统计 </span>
      </div>
      <div>{{ formData.subjects.join("、") }}</div>
    </el-alert>
    <el-alert
      v-if="formData.office != '终端管制室'"
      type="warning"
      :closable="false"
      class="notice-alert"
    >
      <div>
        <b>该练习为{{ formData.office }}使用，</b>
        <span>为避免填写错误</span>
        <b>此处仅显示{{ formData.office }}人员。</b>
        <span>若此处未显示所需人员，</span>
        <b>请提醒学员在个人信息中修改为正确的科室。</b>
      </div>
    </el-alert>
    <div style="border-bottom: 1px solid #e6e6e6; padding-top: 12px">
      <el-form label-width="80px">
        <el-form-item label="受训人员">
          <el-select
            v-model="formData.traineeNumber"
            filterable
            placeholder="请选择受训人员"
            @change="handleTraineeChange"
            style="width: 100%"
            size="small"
          >
            <el-option
              v-for="user in userList"
              :key="user.number"
              :label="user.name"
              :value="user.number"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="培训日期">
          <el-date-picker
            v-model="formData.trainingDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            style="width: 100%"
            size="small"
            :clearable="false"
          ></el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <!-- duplication check -->
    <div v-if="checkResult == 0">
      <!-- checkResul t== 0 -->
      <!-- before check -->
      <el-alert type="info" :closable="false" class="notice-alert">
        <p>请先在上方列表中选择<b>受训人员</b></p>
      </el-alert>
    </div>
    <div v-else-if="checkResult == -1">
      <!-- checkResult == -1 -->
      <!-- is duplicated -->
      <el-alert type="error" :closable="false" class="notice-alert">
        <p>
          已查找到<b>{{ formData.traineeName }}</b
          >在<b>{{ createData.year }}</b
          >年度的<b>{{ createData.title }}</b
          >培训记录，且结果为<b>已通过</b>，确定要再次为<b>{{
            formData.traineeName
          }}</b
          >提交重复的培训记录吗？
        </p>
        <el-button type="danger" @click="checkResult = 2"
          >确定，为{{ formData.traineeName }}提交重复的记录</el-button
        >
      </el-alert>
    </div>
    <div v-else>
      <!-- checkResult == 1 -->
      <!-- check ok or ignore duplication -->
      <div
        class="formView"
        v-for="(item, index) in formData.subjectsComments"
        :key="index"
        style="border-bottom: 1px solid #e6e6e6; padding-top: 12px"
      >
        <div style="font-size: 16px; font-weight: bold; padding: 6px 0">
          <i class="el-icon-edit"></i>
          <span style="padding-left: 8px">{{ item.subject }}</span>
        </div>
        <el-checkbox-group v-model="item.comments">
          <el-checkbox
            v-for="item in getPresetComments(item.subject)"
            :key="item"
            :label="item"
            style="width: calc(100% - 40px); margin: 6px 12px 6px 24px"
          ></el-checkbox>
        </el-checkbox-group>
        <el-input
          size="small"
          v-model="item.commentPlus"
          placeholder="其他评价（选填）"
          style="margin: 6px 0 6px 24px; width: calc(100% - 24px)"
        ></el-input>
        <div style="padding: 6px 0 24px 24px">
          <span style="padding-right: 12px">科目合格：</span>
          <el-radio-group
            v-model="item.pass"
            @change="(value) => handlePassCheck(item.subject, value)"
          >
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否，需加练</el-radio>
          </el-radio-group>
        </div>
      </div>
      <div style="border-bottom: 1px solid #e6e6e6; padding-top: 12px">
        <div style="font-size: 16px; font-weight: bold; padding: 6px 0">
          <i class="el-icon-medal"></i>
          <span style="padding-left: 8px">等级评定</span>
        </div>
        <div
          v-for="(item, index) in formData.evaluations"
          :key="index"
          style="padding: 6px 0 6px 24px"
        >
          <span>{{ item.title }}：</span>
          <el-rate
            v-model="item.value"
            show-text
            :texts="['E', 'D', 'C', 'B', 'A']"
            style="display: inline; padding-left: 12px"
            @change="handleEvaluationChange"
          >
          </el-rate>
        </div>
        <div style="padding: 12px 12px 18px 18px">
          <el-progress
            :text-inside="true"
            :stroke-width="26"
            :percentage="formData.evaluationScore"
            :status="
              formData.evaluationScore > 90
                ? 'success'
                : formData.evaluationScore > 85
                ? null
                : formData.evaluationScore > 80
                ? 'warning'
                : 'exception'
            "
          ></el-progress>
          <el-alert
            type="warning"
            :closable="false"
            v-show="forceUnpass"
            style="margin-top: 12px"
            >等级评定中出现一次“E”或两次“D”评级则本次练习不合格。</el-alert
          >
        </div>
      </div>
      <div style="border-bottom: 1px solid #e6e6e6; padding: 12px 0">
        <div style="font-size: 16px; font-weight: bold; padding: 6px 0">
          <i class="el-icon-s-comment"></i>
          <span style="padding-left: 8px">综合评价</span>
        </div>
        <div style="padding: 6px 0 12px 24px">
          <span style="padding-right: 12px">练习合格：</span>
          <el-radio-group v-model="formData.pass" :disabled="forceUnpass">
            <el-radio label="是">是</el-radio>
            <el-radio label="否">否</el-radio>
          </el-radio-group>
        </div>
        <el-input
          size="medium"
          v-model="formData.coachComments"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="请填写对本次练习的主观评价（不少于20字）"
          style="margin: 0 0 12px 24px; width: calc(100% - 24px)"
        ></el-input>
        <el-alert
          type="info"
          :closable="false"
          style="margin: 0 0 12px 24px; width: calc(100% - 24px)"
          >已填写<b>{{ formData.coachComments.length }}</b
          >字</el-alert
        >
      </div>
      <div style="border-bottom: 1px solid #e6e6e6; padding-top: 12px">
        <div style="font-size: 16px; font-weight: bold; padding: 6px 0">
          <i class="el-icon-s-check"></i>
          <span style="padding-left: 8px">结论</span>
        </div>
        <el-alert
          :title="formData.pass == '是' ? '合格' : '不合格'"
          :type="
            formData.pass == '否'
              ? 'error'
              : formData.failedSubjects.length > 0
              ? 'warning'
              : 'success'
          "
          :description="
            formData.failedSubjects.length > 0
              ? '需加练' +
                formData.failedSubjects.length +
                '个科目：' +
                formData.failedSubjects.join('、')
              : '无需加练'
          "
          show-icon
          :closable="false"
          style="margin: 12px 0 24px 0"
        >
        </el-alert>
      </div>
      <div style="padding: 24px 0; text-align: center">
        <el-button
          type="primary"
          size="small"
          style="width: 50%; max-width: 300px"
          @click="handleEditorSave"
          >提交</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { format } from "@/utils/datetime.js";
export default {
  name: "formContent",
  data() {
    return {
      editorTitle: "",
      formData: null,
      forceUnpass: false,
      checkResult: 0,
      checkResultContent: null,
      createData: null,
      isLoading: false,
      loadingMessage: "",
      // @20240131
      matchedTraineeLastFilled: null,
      matchedCoachLastFilled: null,
    };
  },
  computed: {
    subjects() {
      return this.$store.state.params.subjects;
    },
    evaluations() {
      return this.$store.state.params.evaluations;
    },
    userNumber() {
      return this.$store.getters.userNumber;
    },
    userName() {
      return this.$store.getters.userName;
    },
    exercisesData() {
      return this.$store.state.exercisesValid;
    },
    recordsData() {
      return this.$store.state.coachRecords;
    },
    userList() {
      return this.$store.state.userList.filter(
        (user) =>
          (this.formData.office == "终端管制室" ||
            user.clientOffice == this.formData.office) &&
          user.number != this.userNumber
      );
    },
    tagEffect() {
      return new Date().getSeconds() % 2 == 0 ? "light" : "dark";
    },
  },
  methods: {
    dateFormat: format,
    openWithCreate: function (data) {
      this.createData = data;
      this.resetDefaultFormData();
      this.editorTitle = "填写练习评价";
      this.formData.title = data.title;
      this.formData.year = data.year;
      this.formData.cycle = data.cycle;
      this.formData.type = data.type;
      this.formData.office = data.office;
      this.formData.hours = data.hours;
      this.formData.exerciseID = data.number;
      for (let i = 0; i < data.subjects.length; i++) {
        this.formData.subjects.push(data.subjects[i]);
        this.formData.subjectsComments.push({
          subject: data.subjects[i],
          comments: [],
          commentPlus: "",
          pass: "是",
        });
      }
      for (let i = 0; i < this.evaluations.length; i++) {
        this.formData.evaluations.push({
          title: this.evaluations[i],
          value: 0,
        });
      }
    },
    openWithModify: function (idx) {
      this.formData = JSON.parse(JSON.stringify(this.recordsData[idx]));
    },
    getPresetComments: function (subject) {
      for (let i = 0; i < this.subjects.length; i++) {
        for (let j = 0; j < this.subjects[i].children.length; j++) {
          if (this.subjects[i].children[j].label === subject) {
            return this.subjects[i].children[j].options;
          }
        }
      }
      return [];
    },
    handleEvaluationChange: function (value) {
      if (this.formData.evaluationMin > value) {
        this.formData.evaluationMin = value;
      }
      let countDE = 0;
      this.formData.evaluationScore = 0;
      for (let i = 0; i < this.formData.evaluations.length; i++) {
        if (this.formData.evaluations[i].value == 0) {
          this.formData.evaluationScore = 0;
          // break;
        } else {
          this.formData.evaluationScore +=
            this.formData.evaluations[i].value * 10 + 45;
        }
        if (this.formData.evaluations[i].value == 1) {
          countDE++;
          countDE++;
        } else if (this.formData.evaluations[i].value == 2) {
          countDE++;
        }
      }
      this.formData.evaluationScore = Math.round(
        this.formData.evaluationScore / 6,
        0
      );
      if (countDE >= 2) {
        this.forceUnpass = true;
        this.formData.pass = "否";
      } else {
        this.forceUnpass = false;
      }
    },
    handlePassCheck: function (subject, value) {
      if (value == "是") {
        if (this.formData.failedSubjects.indexOf(subject) > -1) {
          this.formData.failedSubjects.splice(
            this.formData.failedSubjects.indexOf(subject),
            1
          );
        }
      } else {
        if (this.formData.failedSubjects.indexOf(subject) == -1) {
          this.formData.failedSubjects.push(subject);
        }
      }
      this.formData.failedSubjectsCount = this.formData.failedSubjects.length;
      // if (this.formData.failedSubjects.length == 0) {
      //   this.formData.pass = "是";
      // } else {
      //   this.formData.pass = "否";
      // }
    },
    handleTraineeChange: function (number) {
      for (let i = 0; i < this.userList.length; i++) {
        if (this.userList[i].number == number) {
          this.formData.traineeName = this.userList[i].name;
          this.formData.traineeNumber = this.userList[i].number;
          // added user info @20240131
          this.formData.traineeDepartment = this.userList[i].clientDepartment;
          this.formData.traineeOffice = this.userList[i].clientOffice;
          this.formData.traineeGroup = this.userList[i].clientGroup;
          // added dupicate check @20240129
          this.checkDuplicate();
          return;
        }
      }
    },
    handleEditorSave: function () {
      if (this.inspectData()) {
        this.isLoading = true;
        this.loadingMessage = "正在检查重复记录";
        this.$store
          .dispatch("saveRecord", this.formData)
          .then(() => {
            // this.editorDialogVisible = false;
            this.$notify.success("保存成功");
            // this.loadData();
            this.isLoading = false;
            this.$emit("saved");
            return true;
          })
          .catch(() => {
            this.$notify.error("保存失败");
            this.isLoading = false;
            return false;
          });
        // this.$emit("save", this.formData);
      }
    },
    resetDefaultFormData: function () {
      this.formData = {
        number: null,
        title: "",
        year: "",
        cycle: 1,
        type: 1,
        office: "",
        subjects: [],
        hours: 1,
        pass: "是",
        traineeNumber: null,
        traineeName: "",
        traineeDepartment: "",
        traineeOffice: "",
        traineeGroup: "",
        traineeGrade: "",
        traineePost: "",
        traineeLicences: [],
        traineeComments: "",
        coachNumber: this.userNumber,
        coachName: this.userName,
        subjectsComments: [],
        coachComments: "",
        failedSubjects: [],
        failedSubjectsCount: 0,
        evaluations: [],
        evaluationMin: 5,
        evaluationScore: 0,
        trainingDate: this.dateFormat("yyyy-MM-dd"),
        history: [],
        status: 0,
        commitTime: this.dateFormat("yyyy-MM-dd hh:mm:ss"),
        updateTime: this.dateFormat("yyyy-MM-dd hh:mm:ss"),
      };
    },
    inspectData: function () {
      if (
        this.formData.traineeName == "" ||
        this.formData.traineeNumber == null
      ) {
        this.$notify.error("请选择学员");
        return false;
      }
      for (let i = 0; i < this.formData.subjectsComments.length; i++) {
        if (
          this.formData.subjectsComments[i].comments.length === 0 &&
          this.formData.subjectsComments[i].commentPlus.length === 0
        ) {
          this.$notify.error(
            "请填写或勾选" +
              this.formData.subjectsComments[i].subject +
              "的评价"
          );
          return false;
        }
      }
      for (let i = 0; i < this.formData.evaluations.length; i++) {
        if (this.formData.evaluations[i].value === 0) {
          this.$notify.error(
            "请选择" + this.formData.evaluations[i].title + "的评分"
          );
          return false;
        }
      }
      if (
        this.formData.pass == "否" &&
        this.formData.failedSubjects.length == 0
      ) {
        this.$notify.error(
          "如果您认为本次练习不合格，请在对应科目下方选择“否，需加练”"
        );
        return false;
      }
      if (this.formData.coachComments.length < 20) {
        this.$notify.error("请填写主观评价，不少于20字");
        return false;
      }
      return true;
    },
    checkDuplicate: function () {
      // added duplication check in 2024-01-28
      this.checkResult = 0;
      this.isLoading = true;
      this.loadingMessage = "正在检查重复记录";
      let payload = {
        year: [this.createData.year],
        title: [this.createData.title],
        pass: ["是"],
        traineeName: [this.formData.traineeName],
        traineeNumber: [this.formData.traineeNumber],
      };
      this.axios
        .post("api/query_records_lite.php", {
          user: null,
          payload,
        })
        .then((response) => {
          if (response.data && response.data.length > 0) {
            this.checkResult = -1;
            this.checkResultContent = response.data[0];
          } else {
            this.checkResult = 1;
          }
          this.isLoading = false;
        })
        .catch((error) => {
          console.error("检查重复记录出错", error);
          this.$notify.error({
            title: "检查重复记录出错",
            message: error.message,
          });
          this.isLoading = false;
        });
    },
    findTraineeLastFilled: function () {
      // let payload = {
      //   traineeNumber: [this.formData.traineeNumber],
      // };
      // let url = "api/query_records_lite.php?limit=1&order=DESC";
      // this.axios
      //   .post(url, { user: null, payload })
      //   .then((response) => {
      //     console.log(response.data);
      //     if (response.data && response.data.length == 1) {
      //       this.matchedTraineeLastFilled = {};
      //     }
      //   })
      //   .catch((error) => {
      //     console.error(error);
      //   });
    },
    findCoachLastFilled: function () {
      // let payload = {
      //   coachNumber: [this.formData.coachNumber],
      //   exerciseID: [this.formData.exerciseID],
      // };
      
    },
  },
};
</script>

<style scoped>
@import "./blinking.css";
@import "./shaking.css";

.office-warning {
  font-weight: bolder;
  /* position: fixed; */
  /* right: 16px; */
  /* top: 80px; */
  /* z-index: 999; */
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.3);
}

.notice-alert {
  font-size: 12px;
  line-height: 16px;
  padding: 4px 6px 6px 6px;
  margin: 0;
  margin-bottom: 12px;
}
</style>
